from faker import Faker
import random
from datetime import datetime, timedelta
from data_mock.utils import MysqlUtils_AI

fake = Faker('zh_CN')

# ========== 癌症配置 ==========
CANCER_TYPES = {
    'C34.90': {'name': '肺恶性肿瘤'},
    'C16.9': {'name': '胃恶性肿瘤'},
    'C18.9': {'name': '结肠恶性肿瘤'},
    'C50.919': {'name': '乳腺恶性肿瘤'},
    'C61': {'name': '前列腺恶性肿瘤'}
}


# ========== 数据生成函数 ==========
def generate_aggr_basefee():
    sql_statements = []
    hospital_code = "HSP001"
    hospital_name = "肿瘤防治中心"

    for day in generate_day_range("2025-08-01", "2025-08-30"):
        records_per_day = 6 if datetime.strptime(day, "%Y-%m-%d").day % 2 else 8

        for i in range(records_per_day):
            cancer_code, cancer_info = random.choice(list(CANCER_TYPES.items()))

            patient_id = f"PT{random.randint(1000, 9999)}"
            visit_sn = f"VIS{random.randint(10000, 99999)}"
            drg_code = f"DRG{random.randint(100, 999)}"
            drg_name = f"{cancer_info['name']}分组"

            total_amount = round(random.uniform(10000, 100000), 2)
            hospital_time = random.randint(3, 30)
            avg_cost_std = round(total_amount / hospital_time * random.uniform(0.8, 1.2), 2)
            group_diff = round(random.uniform(-2000, 3000), 2)

            # 生成随机费用项
            fees = {k: round(random.uniform(100, 5000), 2) for k in list("ABCDEFGHIJKLMN")}
            fees['Z'] = round(random.uniform(50, 500), 2)

            data = {
                **fees,
                'RW': str(round(random.uniform(0.5, 3.0), 2)),
                'adrg_code': f"ADRG{random.randint(100, 999)}",
                'adrg_name': f"{cancer_info['name']}ADRG组",
                'age': str(random.randint(30, 85)),
                'aux_dis_code': random.choice(['I10', 'E11.9', 'E78.5']),
                'aux_dis_name': random.choice(['高血压', '2型糖尿病', '高脂血症']),
                'aux_oper_code': f"OP{random.randint(1000, 9999)}",
                'aux_oper_name': random.choice(['腹腔镜手术', '经皮穿刺活检', '肿瘤切除术']),
                'cc_flag_drg': random.choice(['Y', 'N']),
                'cut_flag': random.choice(['是', '否']),
                'diff_coefficient': str(round(random.uniform(0.8, 1.2), 2)),
                'diff_reason1': random.choice(['药费偏高', '检查项目偏多', '住院日偏长']),
                'diff_reason2': random.choice(['护理费用增加', '材料费增加', '麻醉费偏高']),
                'diff_type': random.choice(['药占比偏高', '平均费用异常', '住院天数异常']),
                'discharge_disease_id': cancer_code,
                'discharge_disease_name': cancer_info['name'],
                'drg_avg_cost_std': avg_cost_std,
                'drg_avg_hospital_time_std': random.randint(7, 18),
                'drg_code': drg_code,
                'drg_name': drg_name,
                'estimate_drg_cost': round(total_amount + group_diff, 2),
                'estimate_total_point': str(round(random.uniform(50, 200), 2)),
                'extend_data1': None,
                'extend_data2': None,
                'from_table': 'b05_1',
                'from_yy_record_id': f"ADM{random.randint(10000, 99999)}",
                'group_clear_diff': group_diff,
                'hospital_average': round(avg_cost_std * random.uniform(0.9, 1.1), 2),
                'hospital_code': hospital_code,
                'hospital_name': hospital_name,
                'hospital_time': hospital_time,
                'main_opr_code': f"OP{random.randint(100, 999)}",
                'main_opr_name': random.choice(['肿瘤切除术', '胃镜检查', '结肠镜检查']),
                'mdc_code': f"MDC{random.randint(10, 99)}",
                'mdc_name': f"{cancer_info['name']}MDC",
                'patient_id': patient_id,
                'patient_id_old': f"OLD_{patient_id}",
                'record_datetime': fake.date_time_between(
                    start_date=datetime.strptime(day, "%Y-%m-%d"),
                    end_date=datetime.strptime(day, "%Y-%m-%d") + timedelta(days=1)
                ).strftime('%Y-%m-%d %H:%M:%S'),
                'record_status': 1,
                'record_update_datetime': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                'risk_flag': random.choice(['是', '否']),
                'row_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                'score': str(round(random.uniform(0.5, 3.0), 2)),
                'total_amount': total_amount,
                'visit_sn': visit_sn,
                'yy_collection_datetime': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                'yy_record_md5': fake.md5(raw_output=False),
                'yy_upload_status': 0,
                'yy_etl_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                'yy_upload_time': None,
                'yy_batch_time': day,
                'yy_record_batch_id': f"BATCH{day}_{i}",
                'yy_backfill_time': None,
                'yy_backfill_status': None,
                'date_for_partition': day
            }

            sql = generate_sql('aggr_basefee', data)
            sql_statements.append(sql)

    return sql_statements


# ========== 辅助函数 ==========
def generate_day_range(start_date, end_date):
    start = datetime.strptime(start_date, "%Y-%m-%d")
    end = datetime.strptime(end_date, "%Y-%m-%d")
    delta = end - start
    return [(start + timedelta(days=i)).strftime("%Y-%m-%d") for i in range(delta.days + 1)]


def generate_sql(table, data):
    columns, values = [], []
    for k, v in data.items():
        columns.append(f"`{k}`")
        if v is None:
            values.append("NULL")
        elif isinstance(v, (int, float)):
            values.append(str(v))
        else:
            escaped_value = str(v).replace("'", "''")
            values.append(f"'{escaped_value}'")
    return f"INSERT INTO `{table}` ({', '.join(columns)}) VALUES ({', '.join(values)});"


# ========== 主执行 ==========
if __name__ == "__main__":
    print("开始生成 aggr_basefee 表数据...")
    records = generate_aggr_basefee()
    MysqlUtils_AI.insert_data_to_hub(records, 'aggr_basefee')
